import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw,  } from 'vue-router'
import Welcome from '../views/Welcome.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Loading from '../components/Loading.vue'
import AppLayout from '../components/layout/AppLayout.vue'
import { useMenuStore } from '../stores/menu'
import { registerAsyncRoutes } from './modules/dynamicRoutes'
import { routeDebugger } from '../utils/routeDebugger'
import ForgetPass from '../views/ForgetPass.vue'

// 静态路由，不包含404路由
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'welcome',
    component: Welcome,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'register',
    component: Register,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/forget-password',
    name: 'forget-password',
    component: ForgetPass,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/loading',
    name: 'loading',
    component: Loading,
    meta: {
      requiresAuth: true
    }
  },
  // 添加仪表盘作为顶级路由确保始终可访问
  {
    path: '/dashboard',
    name: 'AppLayout',
    component: AppLayout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'dashboard',
        component: () => import('@/components/dashboard/DashboardPage.vue'),
        meta: {
          requiresAuth: true,
          title: '控制台'
        }
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫，验证是否需要登录
router.beforeEach(async (to, from, next) => {
  // 检查路由是否明确需要身份验证
  const requiresAuth = to.meta.requiresAuth === true

  // 检查用户是否已登录
  const isLoggedIn = !!localStorage.getItem('accessToken')

  console.log(`路由导航: ${from.path} -> ${to.path}`)
  console.log(`目标路由信息:`, { 
    path: to.path, 
    name: to.name, 
    matched: to.matched.length,
    meta: to.meta 
  })
  console.log(`明确需要认证: ${requiresAuth}, 已登录: ${isLoggedIn}`)

  // 页面刷新处理逻辑 - 放在前面优先处理
  if (to.matched.length === 0 && isLoggedIn) {
    const currentPath = to.path // 保存当前路径用于后续恢复
    console.log('路由未匹配，检测可能是页面刷新导致路由丢失')
    
    // 检查是否是路由恢复阶段的导航
    const fromLoading = from.name === 'loading'
    
    // 如果是从loading页面过来，且matched为0，说明即使加载了动态路由仍然无法匹配，真的是404
    if (fromLoading) {
      console.log('从loading页面导航过来但仍无法匹配路由，确认为404')
      next({ name: '404' })
      return
    }
    
    // 否则是刷新导致的，尝试恢复
    console.log('检测到页面刷新，需恢复路由后再导航到:', currentPath)
    
    // 先导航到loading页
    next({ name: 'loading', params: { redirect: currentPath } })
    return
  }

  // 如果是访问登录或注册页面，确保清除任何可能存在的旧菜单数据
  if (to.name === 'login' || to.name === 'register') {
    const menuStore = useMenuStore()
    menuStore.resetMenuState()
    console.log('导航到登录/注册页面，清除菜单和路由数据')
  }

  // 如果路由需要认证但用户未登录，则重定向到登录页面
  if (requiresAuth && !isLoggedIn) {
    console.log('需要认证但未登录，重定向到登录页')
    next({ name: 'login', query: { redirect: to.fullPath } })
    return
  }

  // 用户已登录情况处理
  if (isLoggedIn) {
    const menuStore = useMenuStore()

    // 如果尝试访问登录/注册页，但已登录，则重定向到控制台
    if (to.name === 'login' || to.name === 'register' || to.name === 'forget-password') {
      next({ name: 'dashboard' })
      return
    }

    // 如果是访问根路径，重定向到dashboard
    if (to.path === '/') {
      next({ name: 'dashboard' })
      return
    }

    // 检查本地是否已缓存路由状态
    const isDynamicRouteAddedLocally = localStorage.getItem('dynamic_route_added') === 'true'
    const currentUser = localStorage.getItem('accessToken')
    const routeUser = localStorage.getItem('route_owner_token')

    // 如果路由所有者不是当前用户，强制重新加载路由
    if (currentUser !== routeUser) {
      console.log('检测到用户变更，强制重新加载路由数据')
      menuStore.resetMenuState()
      localStorage.setItem('route_owner_token', currentUser || '')
      next({ name: 'loading' })
      return
    }

    // 如果本地显示路由已添加，但store没更新，则同步store状态
    if (isDynamicRouteAddedLocally && !menuStore.isDynamicRouteAdded) {
      console.log('从本地缓存恢复路由状态')
      // 获取本地菜单数据
      const response = await menuStore.getUserMenu(false) // 不强制刷新，优先使用缓存

      if (response.success && response.data) {
        // 重新注册动态路由
        registerAsyncRoutes(router, menuStore.dynamicMenuList)
        // 更新store状态
        menuStore.setDynamicRouteAdded(true)
        // 记录路由所有者
        localStorage.setItem('route_owner_token', currentUser || '')
        
        // 打印详细的路由信息
        routeDebugger.printAllRoutes(router)

        // 如果目标是loading页面，直接去dashboard
        if (to.name === 'loading') {
          next({ path: '/dashboard' })
          return
        }

        // 否则继续原始导航
        next()
        return
      }
    }

    // 如果菜单尚未加载，但不是前往loading页面
    if (!menuStore.isDynamicRouteAdded && to.name !== 'loading') {
      console.log('需要加载动态路由，先跳转到loading页面')
      next({ name: 'loading' })
      return
    }

    // 如果正在loading页面，且菜单未加载
    if (to.name === 'loading' && !menuStore.isDynamicRouteAdded) {
      try {
        console.log('loading页面加载菜单...')
        // 获取菜单数据，这里不强制刷新，会优先使用本地缓存
        const response = await menuStore.getUserMenu()

        if (response.success && response.data) {
          // 注册动态路由
          registerAsyncRoutes(router, menuStore.dynamicMenuList)

          // 标记动态路由已加载
          menuStore.setDynamicRouteAdded(true)

          // 记录路由所有者
          localStorage.setItem('route_owner_token', currentUser || '')

          // 打印详细的路由信息
          routeDebugger.printAllRoutes(router)

          console.log('动态路由已加载，准备导航')

          // 获取重定向路径（如果有）
          const redirectPath = to.params.redirect || '/dashboard'
          console.log(`尝试导航到: ${redirectPath}`)

          // 导航到重定向路径或仪表盘
          next({ path: redirectPath.toString() })
          return
        } else {
          console.error('菜单加载失败，返回登录页')
          next({ name: 'login' })
          return
        }
      } catch (error) {
        console.error('加载菜单失败:', error)
        next({ name: 'login' })
        return
      }
    }

    // 如果路由到不存在的页面且已加载动态路由
    if (to.matched.length === 0 && menuStore.isDynamicRouteAdded) {
      console.log('路径不存在，导航到404页面')
      console.log('当前已注册的所有路由:', router.getRoutes().map(r => ({ path: r.path, name: String(r.name || '') })))
      // 记录查找不到路由的路径
      console.error(`未能匹配路由: ${to.path}, 请检查菜单配置和路由注册`)
      
      next({ name: '404' })
      return
    }

    // 如果动态路由已加载，且要前往的是loading页面，直接去dashboard
    if (menuStore.isDynamicRouteAdded && to.name === 'loading') {
      next({ path: '/dashboard' })
      return
    }
  }

  console.log('继续正常导航到目标页面:', to.fullPath)
  next()
})

// 在路由守卫设置完成后，最后添加404路由
// 这确保了它不会意外捕获其他有效路由
router.addRoute({
  path: '/:pathMatch(.*)*',
  name: '404',
  component: () => import('../views/error/404.vue'),
  meta: {
    hidden: true,
    requiresAuth: false
  }
})

export default router 

// 全局打印路由函数，用于控制台调试
// 挂载到window对象以便在浏览器控制台中使用
if (typeof window !== 'undefined') {
  // @ts-ignore
  window.printRoutes = () => {
    console.clear();
    routeDebugger.printAllRoutes(router);
    return 'Routes printed to console';
  };

  // 添加更多调试函数
  // @ts-ignore
  window.printRouteTree = () => {
    console.clear();
    routeDebugger.printRouteTree(router);
    return 'Route tree printed to console';
  };

  // @ts-ignore
  window.printDynamicRoutes = () => {
    console.clear();
    routeDebugger.printDynamicRoutes(router);
    return 'Dynamic routes printed to console';
  };

  // @ts-ignore
  window.findRoute = (search: string) => {
    console.clear();
    routeDebugger.findRoute(router, search);
    return `Search results for "${search}" printed to console`;
  };

  // 添加路由统计和分析功能
  // @ts-ignore
  window.analyzeRoutes = () => {
    console.clear();
    routeDebugger.analyzeRoutes(router);
    return 'Route analysis completed';
  };

  // 添加系统路由检查功能
  // @ts-ignore
  window.checkSystemRoutes = () => {
    console.clear();
    routeDebugger.checkSystemRoutes(router);
    return 'System route check completed';
  };

  // 添加专门用于分别计算和打印动态路由和静态路由的函数
  // @ts-ignore
  window.countRoutesByType = () => {
    console.clear();
    routeDebugger.countRoutesByType(router);
    return 'Routes counted and printed by type';
  };

  // 添加简单打印动态路由和静态路由个数的函数
  // @ts-ignore
  window.printRouteCounts = () => {
    routeDebugger.printRouteCounts(router);
    return 'Route counts printed';
  };

  // 添加查找缺失路由的功能
  // @ts-ignore
  window.findMissingRoutes = () => {
    console.clear();
    routeDebugger.findMissingRoutes(router);
    return 'Missing routes analysis completed';
  };

  // 手动添加特定路由的功能
  // @ts-ignore
  window.addMissingOperLogRoute = () => {
    try {
      // 检查路由是否已存在
      const exists = router.hasRoute('operlog') || router.getRoutes().some(r => 
        r.path.includes('/system/log/operlog') || 
        (r.name && String(r.name).includes('operlog'))
      );
      
      if (exists) {
        console.log('%c路由已存在，无需添加', 'color: #E6A23C; font-weight: bold;');
        return '路由已存在，无需添加';
      }
      
      // 添加缺失的操作日志路由
      router.addRoute('AppLayout', { 
        path: '/system/log/operlog', 
        name: 'operlog', 
        component: () => import('@/views/system/log/operlog/index.vue'), 
        meta: { 
          requiresAuth: true, 
          title: '操作日志',
          icon: 'list'
        } 
      });
      
      console.log('%c成功添加操作日志路由', 'color: #67C23A; font-weight: bold;');
      
      // 打印更新后的路由列表
      routeDebugger.printAllRoutes(router, '更新后的路由列表');
      return '操作日志路由已添加';
    } catch (error) {
      console.error('添加路由失败:', error);
      return `添加路由失败: ${error}`;
    }
  };
} 